package com.jsd.demo.utils;

//import com.gogbuy.uppweb.exception.BaseException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.*;

/* *
 *版本：3.3
 *日期：2012-08-14
 *说明：
 *
 */
@Component
public class UppCore {

    private static final Logger logger = LoggerFactory.getLogger(UppCore.class);

    /**
     * 获取签名数据 MD5
     *
     * @param Params        业务参数
     * @param signKey       密钥
     * @param input_charset 编码
     * @return
     */
    public static String getHmac(Map Params, String signKey,
                                 String input_charset) {
        // 过滤空值、sign与sign_type参数
        Map<String, String> sParaNew = UppCore.paraFilter(Params);
        // 由于notify有两个参数...,这里进行处理 //不知道啥逻辑，先注释掉
//        String notifyURL = sParaNew.get("notifyURL");
//        if (notifyURL != null && notifyURL.contains("?listener")) {
//            notifyURL = notifyURL.replace("?listener", "&listener");
//            sParaNew.put("notifyURL", notifyURL);
//        }

        // 获取待签名字符串
        String preSignStr = UppCore.createLinkString(sParaNew);

        logger.info("signKey:" + signKey);
        logger.info("input_charset:" + input_charset);
        String hmac = UPPMD5.sign(preSignStr, signKey, input_charset);
        return hmac;
    }

    /**
     * 过滤 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    private static Map<String, String> paraFilter(Map<String, String> sArray) {

        Map<String, String> result = new TreeMap<>();

        if (sArray == null || sArray.size() <= 0) {
            return result;
        }

        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("")
                    || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")
                    || key.equalsIgnoreCase("action")
                    || key.equalsIgnoreCase("hmac")) {
                continue;
            }
            result.put(key, value);
        }

        return result;
    }

    /**
     * 组装排序 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        logger.info("'''''''''prestr:" + prestr);
        return prestr;
    }
}

